from flask import Flask, render_template
from flask_socketio import emit, SocketIO
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
import app.myopenai as mo
import app.starfire as sf
db = SQLAlchemy()

def create_app():
    app = Flask(__name__,static_folder='./dist',template_folder = "./dist")
    CORS(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cloudserver.db'
    db.init_app(app)

    with app.app_context():
        # 确保在应用上下文中创建所有表
        db.create_all()

    # 在应用上下文中导入蓝图和模型
    from .user import user_bp
    from .project import project_bp
    from .dataset import dataset_bp
    from .moxing import moxing_bp
    from .models import User, Dataset, Model, Apply, Project

    # 注册蓝图
    app.register_blueprint(user_bp)
    app.register_blueprint(project_bp)
    app.register_blueprint(dataset_bp)
    app.register_blueprint(moxing_bp)

    # 初始化 Flask-Admin
    admin = Admin(app, name='CloudServer Admin', template_mode='bootstrap3')
    for model in [User, Dataset, Model, Apply, Project]:
        admin.add_view(ModelView(model, db.session, category='Models'))

    socketio = SocketIO(app, cors_allowed_origins="*")

    @socketio.on('chat')
    def chat(message):
        response = sf.starfire(message)
        for chat_generation in response:
            content = chat_generation[0].message.content
        # print("content:", content)
        emit('chat_output', {'output': content})
        # print("response:", response.content)

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def index(path):
        return render_template('index.html')

    return app
